// pages/reportFormWeek/reportFormWeek.js
const app = getApp();
import * as echarts from '../../ec-canvas/echarts';
import CommonService from '../../utils/service/commonService.js';
const util = require('../../utils/util');

//图表对象
let Chart=null;

Page({

  /**
   * 页面的初始数据
   */
  data: {
    //图表
    ec: {
      //延迟加载
      lazyLoad: true 
    },    
    //是否显示图表（避免遮挡）
    showChart:true,    
    //无数据
    showNoData:false,    
    //图表配置
    chartSet:{
      //图表类型
      type:'line',    
      //颜色
      barColor:'#FF3300',
      //y轴标题
      title:''
    },
    //选择周
    showWeek:false,
    //周的选择列表
    weekList:[],
    //显示的周
    weekWord:'上周',
    //选中的周
    selectedWeek:null,
    //周统计到几周前
    weekNum:7,
    //切换按钮
    showAllBtn:true,
    //页码
    page: 1,
    //是否无更多
    notMore: true,
    //更多的按钮文字
    moreWord:'查看更多',
    //显示更多按钮
    showMoreBtn:false,
    //部门数据
    departList:[],
    //一级部门列表
    departOne:[],
    //部门选择框
    showDepart:false,   
    //选择的部门id
    departId: null,
    //选择的部门名字
    departName: '',
    //搜索项目输入的值
    valueSearchProject:'',
    //图表数据
    list:[] 
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    //当前部门
    this.setData({
      departId: app.globalData.userInfo.depart,
			departName: app.globalData.userInfo.departObj[0].name
    })
    
    //计算本周和上几周的日期
    this.getWeekList();

    //获取图表数据
    this.getChartData();  
  },

  //获取图表数据
  getChartData(){
    this.setData({ 
      moreWord: '查看更多'      
    })

    //图表组件
    this.echartsComponnet = this.selectComponent('#mychart'); 
    
    let week=this.data.selectedWeek;  
    let startDate=new Date(week.startDate);
    let weekDate=[];
    let day = startDate.getDay() || 7;
    let n=0;

    //如果是本周    
    if(this.data.selectIndex==0){
      n=new Date().getDay();
    }else{
      n=7;
    }

    //计算一周日期（用于图表展示）
    for(let i=1;i<=n;i++){
      weekDate.push(util.timeFormatDay(new Date(startDate.getFullYear(), startDate.getMonth(), startDate.getDate() + i - day)));
    }
    this.setData({ 
      weekDate: weekDate
    }) 

    let param={
      beginDate:week.start,
      endDate:week.end,
      //departId:[this.data.departId],
    }  

    CommonService.reportByWeek(param).then(res=>{
      if(res.data.data && res.data.data.result && res.data.data.result.length){
        let result=res.data.data.result;

        console.log('周统计报表');
        console.log(result);

        this.setData({ 
          list: result
        })

        //分页获取列表
        this.getList();
        
      }else{
        this.setData({ 
          showNothing: true
        })
      }
    }).catch((error) => {                
    })  
  },

  //分页获取列表
  getList(){
    let result=this.data.list;
    let weekDate=this.data.weekDate;

    this.setData({ 
      moreWord: '查看更多'
    })

    //图表组件
    this.echartsComponnet = this.selectComponent('#mychart');    

    let showList=this.getPageData(result,10,this.data.page);

    console.log('当前10条');
    console.log(showList);  

    if(showList.length){
      //如果不足一页就不显示更多按钮了
      if(showList.length==10){
        this.setData({
          showMoreBtn: true
        })
      }

      //星期数据    
      let xArr=weekDate;
      //项目数据      
      let yArr=[];

      showList.forEach(item => {
        yArr.push(item.memberTypeName ? item.memberTypeName : '暂无型号');

        //日期map
        let maps=new Map();
        weekDate.forEach(item => {
          maps.set(item,0);
        });

        //无数据的补全日期
        let dateObj=item.dateObj;
        for(let i=0;i<dateObj.length;i++){
          maps.set(dateObj[i].date, dateObj[i].cleanArea); 
        }
        item.dateMap=maps;
      });  

      //series数据
      let sArr=[];
      for(let i=0;i<weekDate.length;i++){
        let areaArr=[];
        showList.forEach(item => {
          areaArr.push({
            name:item.projectName,
            value:parseInt(item.dateMap.get(weekDate[i]))
          })
        }); 

        sArr.push({
          name: weekDate[i],
          type: 'bar',
          stack: 'total',
          label: {
            show: false  
          },
          emphasis: {
            focus: 'series'
          },
          barWidth : 30,
          data: areaArr
        });
        
      }

      let chartData={
        "xData": xArr,
        "yData": yArr,
        "sData": sArr
      }

      //判断图表是否第一次绘制
      this.isHaveChart(Chart,this.echartsComponnet,this.data.chartSet,chartData);  
    }else{
      this.setData({
        notMore: false
        
      })
      if(this.data.page==1){
        this.setData({ 
          showNothing: true
        })
      }else{
        this.setData({ 
          moreWord: '返回',
          page:0,
          notMore: true,
          showNothing: false
        })
      }
    } 
  },

  /* 手动分页
  arr：数组
  n：每次取的数量
  idx：从第几个开始取
  */
  getPageData(arr,n,idx){
    let index=(idx-1)*10;
    let pages=[];

    for(let i=1;i<=n;i++){
      if(arr[index]){
        pages.push(arr[index]);
        index++;
      }else{
        break;
      }
    }

    return pages;
  },

  //刷新列表和页码
  refreshListAndPage(){
    this.setData({
      page:1,
      notMore: true,
      showNothing: false,
      showMoreBtn: false 
    })
    this.getChartData();
  },

  //判断图表是否第一次绘制
  isHaveChart(chartObj,componnetObj,setObj,dataObj){
    if (!chartObj){      
      //如果是第一次绘制，则初始化图表
      this.init_echarts(chartObj,componnetObj,setObj,dataObj); 
    }else{
      //更新图表数据
      this.setOption(chartObj,setObj,dataObj);
    }    
  },

  //初始化图表
  init_echarts: function (chartObj,componnetObj,setObj,dataObj) {      
    componnetObj.init((canvas, width, height) => {      
      chartObj = echarts.init(canvas, null, {
        width: width,
        height: height
      });

      this.setOption(chartObj,setObj,dataObj);
      
      return chartObj;       
    });
  },

  //更新图表数据
  setOption: function (chartObj,setObj,dataObj) {    
    //清除
    chartObj.clear();
    //设置新数据
    chartObj.setOption(this.getOption(chartObj,setObj,dataObj));  
  },

  //指定图表的配置项和数据
  getOption: function (chartObj,setObj,dataObj) {
    let option = {
      color:['#F40000','#F37502','#F3DC2A','#219F6D','#33CFF4','#2064EE','#8C40F4'],      
      legend: {
        icon: 'circle',
        textStyle: {              
          padding: [0, 15, 0, 0]
        },
        data: dataObj.xData
      },
      tooltip: {
        //show:false,
        trigger: 'axis',
        axisPointer: {
          type: 'shadow'
        },
        //confine: true,
        position: ['60%', '20%'],
        //alwaysShowContent:false
        // formatter: function(param){
        //   console.log(param);
        //   //return param;
        // }     
      },
      grid: {
        top: '18%',
        right: '7%',
        bottom: '0',
        left: '4%', 
        containLabel: true
      },
      xAxis: {
        type: 'value',
        axisLabel: {
          fontSize : 14,
          rotate:20            
        }
      },
      yAxis: {
        type: 'category',
        axisLabel: {
          fontSize : 13             
        },
        data: dataObj.yData
      },
      series:dataObj.sData
    };  
    return option;
  },  

  //隐藏图表
  hideChart(){
    this.setData({       
      showChart:false      
		})
  },

  //显示图表
  showChart(){
    this.setData({       
      showChart:true
		})
  },

  //计算本周和上几周的日期
  getWeekList(){
    //当前日期
    let today=new Date();
    let day = today.getDay() || 7;
    //本周周一
    let monday=new Date(today.getFullYear(), today.getMonth(), today.getDate() + 1 - day);
    //本周周日
    let sunday=new Date(today.getFullYear(), today.getMonth(), today.getDate() + 7 - day);  
    
    //本周
    let weekList=[{
      text:util.timeFormatDay(monday) +' 至 '+ util.timeFormatDay(today),                     
      start:util.timeFormatDay(monday),
      startDate:new Date(monday).getTime(),
      end:util.timeFormatDay(today),
      word:util.timeFormatDay(monday).slice(5) +' 至 '+ util.timeFormatDay(today).slice(5) 
    }];

    let n=this.data.weekNum;    
    for(let i=1;i<=n;i++){        
      let lastMonday=util.countPrevDay(monday,7);
      let lastSunday=util.countPrevDay(sunday,7);
      
      let obj={ 
        text:util.timeFormatDay(lastMonday) +' 至 '+ util.timeFormatDay(lastSunday),
        start:util.timeFormatDay(lastMonday),
        startDate:new Date(lastMonday).getTime(),
        end:util.timeFormatDay(lastSunday),
        word:util.timeFormatDay(lastMonday).slice(5) +' 至 '+ util.timeFormatDay(lastSunday).slice(5)
      }           
      weekList.push(obj);
    }  
    
    this.setData({ 
      weekList: weekList,
      //周统计初始参数赋值
      selectedWeek:{
        start:weekList[1].start,
        startDate:weekList[1].startDate,
        end:weekList[1].end
      }     
    })
  }, 

  //显示选择周的日期
  onShowWeekSelect(){
    this.setData({ 
			showWeek: true
    })
    //隐藏图表
    this.hideChart();
  },

  //隐藏选择周的日期
  onCloseWeek(){
    this.setData({ 
			showWeek: false
    })
    //显示图表
    this.showChart();
  },

  //确认选择周的日期
  onConfirmWeek(e){
    let obj=e.detail.value;
    
    this.setData({ 
      weekWord: obj.word,
      selectedWeek:obj,
      selectIndex:e.detail.index
    })
    
    //隐藏选择周的日期
    this.onCloseWeek();

    //周统计数据    
    this.refreshListAndPage();
  },  

  //翻页
  onNext(){
    if(this.data.notMore){
      this.setData({ 
        page: this.data.page + 1
      })
      this.getList();
    }
  },

  //显示部门选择框
  onShowDepart(){
    this.setData({ 
			showDepart: true
    })
    //隐藏图表
    this.hideChart(); 
    //查询一级子部门
    this.findDepartFirst();   
  },

  //隐藏部门选择框
  onCloseDepart(){
    this.setData({ 
			showDepart: false
    })
    //显示图表
    this.showChart();
  },

  //选择部门
  onChangeDepart(event) {
    const { picker, value, index } = event.detail;
    let arr=picker.getValues();
    this.findChildren(arr[0].id);       
  },   

  //确认部门
  onConfirmDepart(e){  
    let arr=e.detail.value; 
    if(arr[1]){
      this.setData({
        departId: arr[1].id,
        departName: arr[1].text
      });
    }else{
      this.setData({
        departId: arr[0].id,
        departName: arr[0].text
      });
    }
    
    this.onCloseDepart();

    //周统计数据    
    this.refreshListAndPage();
  },

  //查询一级子部门
  findDepartFirst(){
    let param = {
      isAuth: false,
      className: 'depart',
      data: {
        searchAll: true,
        fid: app.globalData.userInfo.depart,
        selectFields: ["id", "fid","name"]
      },
      sort: {
        name: -1
      },
    }

    //项目名称模糊查询
    if(this.data.valueSearchProject){
      param.data.name='%'+this.data.valueSearchProject+'%'
    }

    CommonService.goFindList(param).then(res=>{
      if(res.data.data && res.data.data.result && res.data.data.result.length){
        let result=res.data.data.result;
        let arr=[];
        result.forEach(item => {
          arr.push({
            id:item.id,
            text:item.name,
          });
        });

        this.setData({ 
          departOne: arr
        })

        //查询子部门
        this.findChildren(result[0].id);
      }else{
        this.setData({ 
          departList: []
        })
      }
    }).catch((error) => {
      this.setData({ 
        departList: []
      })
    })
  },
  
  //查询子部门
  findChildren(fid){
    let param = {
      isAuth: false,
      className: 'depart',
      data: {
        searchAll: true,
        fid: fid,
        selectFields: ["id", "fid","name"],
        sort: {
          name: -1
        },
      }
    }

    CommonService.goFindList(param).then(res=>{
      let departOne=this.data.departOne;      
      //处理分类数据格式
      let departList=[
        {
          values: departOne,
          className: 'column1',
        }        
      ]

      if(res.data.data && res.data.data.result && res.data.data.result.length){
        let result=res.data.data.result;
        let arr=[];
        result.forEach(item => {
          arr.push({
            id:item.id,
            text:item.name,
          });
        });          
        departList.push({
          values: arr,
          className: 'column2'
        });

      }else{
        departList.push({
          values: [],
          className: 'column2'
        });
      }

      this.setData({ 
        departList: departList
      })

    }).catch((error) => {
    })
  },  

  //查看所有部门数据
  onLookAll(){
    this.setData({
      departId: app.globalData.userInfo.depart,
      departName: app.globalData.userInfo.departName,
      valueSearchProject:''
    })

    this.onCloseDepart();

    //周统计数据    
    this.refreshListAndPage();
  },

  //选择项目-搜索
  onChangeProjectName(e){
    this.setData({
      valueSearchProject: e.detail  
    })  

    //查询一级子部门
    this.findDepartFirst();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  }
})